<template>
  <base-breadcrumb>
    <a-row :gutter="10" class="page-height">
      <!-- 树搜索 -->
      <a-col :span="6">
        <a-card class="page-height-tree">
          <title-name title="组织架构" />
          <!-- 公司组织树搜索 -->
          <tree-organization
            ref="treeOrganization"
            :expand-by-auto="true"
            :selected-keys.sync="selectedKeys"
            :select-options.sync="selectOptions"
            :contain-virtual="$route.meta.isCompany"
            :org-query="treeQuery"
            :show-child-with-search="true"
            :filter-fn="handleFilterTree"
            @loader="getTable"
            @onOrgSelect="orgSelect"
            :isFilterNode.sync="isFilterNode"
            :isFilterIcon.sync="isFilterIcon"
            @updateIsFilterNode="updateIsFilterNode"
            :isBranchOpen="true"
            :initExpandAll="true"
          />
        </a-card>
      </a-col>
      <a-col :span="18" class="page-height-list-wrapper">
        <searchData :search-data="searchArr" @search="handleSearch" />
        <a-card class="mb20 page-height-list">
          <list-table ref="table" row-key="id" :columns="columns" :request="loadData" :alert="true">
            <div slot="prefix" v-if="!$route.meta.isCompany" class="pub-table-action-btn">
              <a-button v-if="!!selectedKeys[0]" :disabled="enable" v-btnPermission="'sy_001_add_01'" icon="plus" class="btn_right" type="primary" @click="handleUpdate('add')"> 新增下级组织机构 </a-button>
              <a-button v-if="!!selectedKeys[0]" v-btnPermission="'sy_001_edn_03'" class="btn_right" icon="edit" type="primary" @click="handleEditCurrent"> 编辑当前所选组织 </a-button>
            </div>
            <template slot="type" slot-scope="text">
              <span v-show="text === '1'">单位</span>
              <span v-show="text === '2'">部门</span>
              <span v-show="text === '7'">虚拟部门</span>
              <span v-show="text === '8'">其他</span>
            </template>
            <template slot="enable" slot-scope="text">
              {{ text === 1 ? '可用' : '不可用' }}
            </template>
            <template slot="pName" slot-scope="text">
              {{ text || '无' }}
            </template>
            <template slot="operation" slot-scope="text, record">
              <MoreButton>
                <a v-btnPermission="lookBtnCode" @click="handleUpdate('look', record)">查看</a>
                <a v-if="!$route.meta.isCompany" v-btnPermission="'sy_001_edi_04'" @click="handleUpdate('edit', record)">编辑</a>
                <a v-if="!$route.meta.isCompany" v-btnPermission="'sy_001_del_05'" @click="handleUpdate('delete', record)">删除</a>
              </MoreButton>
            </template>
          </list-table>
        </a-card>
      </a-col>
    </a-row>
    <!-- 弹出框 -->
    <div>
      <UpdateOrg-modal ref="UpdateOrgModal" :visible.sync="modalVisible" :transmit="addOrEditData" @closeModal="closeModal"></UpdateOrg-modal>
    </div>
  </base-breadcrumb>
</template>

<script>
import TreeOrganization from '@/components/businessComponents/TreeOrganization' // 树
import { searchArr, columns } from './model'
import { getOrgManageList, deleteOrgList } from '@/api/system/system'
import UpdateOrgModal from './UpdateOrgModal'
export default {
  name: 'BaseOrganizationManage',
  components: {
    TreeOrganization,
    UpdateOrgModal
  },
  data() {
    return {
      isFilterIcon: true, //控制图标是否隐藏
      isFilterNode: false, //树节点是否隐藏节点
      searchArr: searchArr,
      columns: columns,
      chooseData: 0,
      tableData: [],
      selectedRowKeys: [],
      selectedRows: [],
      selectedKeys: [], // 选中节点
      selectOptions: {}, // 选中节点对象
      selectedOrg: {}, //选择左侧树节点
      enable: false, //选中的节点是否可用
      orgId: '',
      modalVisible: false,
      pagination: {
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 10 // 默认当前页显示数据的大小
      },
      pathName: this.$route.path,
      isTableList: false,
      queryParam: {}, // 搜索参数
      addOrEditData: {}, //编辑和新增的传参
      loadData: (parameter) => {
        if (!this.isTableList) return false
        this.enable = this.selectOptions?.data?.enable === 1 ? false : true
        this.enable = this.selectOptions?.data?.parentId ? this.enable : false //顶级节点判断
        let searchData = {
          ...this.queryParam,
          pid: this.selectedKeys[0],
          baseOrgType: 1,
          resultWithLeaderName: true // 查询部门分管领导
        }
        searchData.cascade = searchData.pid ? true : false
        if (this.selectedOrg) {
          searchData.pid = this.selectedOrg.id
        }
        if (!this.isFilterNode) {
          searchData.enable = 1
        } else {
          delete searchData.enable
        }
        const requestParameters = Object.assign({ pageNum: parameter.pageNo, pageSize: parameter.pageSize }, searchData)

        return getOrgManageList(requestParameters).then((res) => {
          res.code = res.status
          res.totalSize = res.data.total
          res.data = res.data.list
          res.data.forEach((item) => {
            if (this.selectOptions?.id === item.id) {
              this.$nextTick(() => {
                this.enable = item.enable === 1 ? false : true
              })
            }
          })
          return res
        })
      } // 加载数据方法 必须为 Promise 对象
    }
  },
  computed: {
    treeQuery() {
      // 公司架构和基本架构的查询参数不同
      return {
        baseOrgType: 1,
        containVirtual: ''
      }
    },
    lookBtnCode() {
      return this.$route.meta.isCompany ? 'sy_002_loo_01' : 'sy_001_loo_02'
    }
  },
  mounted() {
    this.$refs.treeOrganization.getList().then((res) => {
      this.getTable()
    })
    console.log('mounted-----------table的Path', this.pathName)
    // 监听详情页返回刷新列表
    //this.pathName取的值是this.$route.path
    this.$bus.$on('handleRefresh' + this.pathName, () => {
      console.log('--------------------收到了，刷新刷新刷新----------------', this.pathName)
      this.getTable()
    })
  },
  beforeDestroy() {
    console.log('beforeDestroy-------table的Path', this.pathName)
    this.$bus.$off('handleRefresh' + this.pathName)
  },
  methods: {
    updateIsFilterNode() {
      this.isFilterNode = !this.isFilterNode
      this.handleSearch(this.queryParam)
    },
    handleFilterTree(data) {
      if (!this.$route.meta.isCompany) {
        if (this.isFilterNode) {
          return data.label !== '分包商'
        } else {
          return data.label !== '分包商' && data.data.enable === 1
        }
      }
      return true
    },
    /**
     *@desc  新增  编辑  查看 删除
     *@param {}
     */
    handleUpdate(type, data = {}) {
      this.$refs.UpdateOrgModal.activeKey = 'Basic'
      const commonHandler = () => {
        this.modalVisible = true
        this.addOrEditData = {
          isCompany: this.$route.meta.isCompany,
          pageType: type,
          id: data.id || '',
          parent: data.parent,
          parentId: data.parentId || data.pid || this.selectOptions.id // 当新增下级时，需要使用选中的节点作为父级组织
        }
      }

      const typeMap = {
        add: commonHandler,
        edit: commonHandler,
        look: commonHandler,
        delete: () => {
          this.handleDeleteWarning(data)
        }
      }
      typeMap[type] && typeMap[type]()
    },
    /**
     *@desc  获取组织列表
     *@param {}
     */
    getTable() {
      let that = this
      if (that.selectedKeys && that.selectedKeys.length > 0) {
        this.isTableList = true
        this.$refs.table.refresh(true)
      }
    },
    orgSelect(org) {
      this.selectedOrg = org
      this.pagination.defaultCurrent = 1
      if (!org) {
        this.selectedKeys[0] = ''
        this.handleSearch(this.queryParam)
      }
    },
    /**
     *@desc  关闭模态框
     *@param {}
     */
    closeModal(value) {
      this.modalVisible = false
      if (value === 'submit') {
        this.$refs.treeOrganization.getList().then((res) => {
          this.handleSearch(this.queryParam)
        })
      }
      // this.getTable()
    },
    /**
     *@desc  table表格搜索
     *@param {}
     */
    handleSearch(value) {
      // this.handleTable(value)
      value && (this.queryParam = value)
      this.$refs.table.refresh(true)
    },
    /**
     *@desc  table表格列表
     *@param {}
     */
    handleTable(params) {
      let _this = this
      let searchData = {
        ...params,
        pid: _this.selectedKeys[0],
        pageNum: _this.pagination.defaultCurrent,
        pageSize: _this.pagination.defaultPageSize,
        resultWithLeaderName: true // 查询部门分管领导
      }
      getOrgManageList(searchData).then((res) => {
        if (res.status === 200) {
          _this.pagination.total = res.data.total
          _this.tableData = res.data.list
        }
      })
    },
    /**
     *@desc  table表格选中
     *@param {}
     */
    onSelectChange(selectedRowKeys, selectedRows) {
      let _this = this
      _this.selectId = []
      selectedRows.map((item) => {
        // 选中id
        _this.selectId.push(item.id)
      })
      this.chooseData = this.chooseData + selectedRows.length
      _this.selectedRowKeys = selectedRowKeys
      _this.selectedRows = selectedRows
    },
    handleEditCurrent() {
      const record = this.selectOptions.data || this.selectOptions
      // this.$refs.UpdateOrgModal.orgIdDisabled = true
      this.handleUpdate('edit', record, null, true)
    },
    /**
     *@desc  table列表删除
     *@param {}
     */
    handleDeleteWarning(record) {
      let _this = this
      _this.$confirm({
        title: `你确定要删除${record.name}吗？`,
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          _this.handleDelete(record)
        },
        onCancel() {
          // console.log('Cancel');
        }
      })
    },

    handleDelete(record) {
      let _this = this
      let params = {
        id: record.id
      }
      deleteOrgList(params)
        .then((res) => {
          if (res?.data?.code == '200') {
            //删除成功
            _this.$refs.treeOrganization.getList().then((res) => {
              this.$message.success('删除成功')
              _this.getTable()
            })
          } else {
            this.$message.error(res?.data?.msg || '删除失败')
          }
        })
        .catch((err) => {
          console.log('失败', err)
          //删除失败
        })
    }
  }
}
</script>